package com.itheima.tanhua.apiImpl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.pojo.mongo.RecommendUser;
import com.itheima.tanhua.api.mongodb.RecommendApi;
import com.itheima.tanhua.pojo.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendApiImpl implements RecommendApi {


    //注入模板类
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 获取缘分最高值的数据对象 集合对象
     * @param uid
     * @return
     */
    @Override
    public RecommendUser getByToUserId(Long uid) {
        //toUserId等于id并且降序排序的第一个
        Query query=Query.query(Criteria.where("toUserId").is(uid))
                         .with(Sort.by(Sort.Order.desc("score")))
                         .limit(1);
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    //获取数据并分页展示
    @Override
    public List<RecommendUser> getData(Long uid) {
        //toUserId等于id并且降序排序的第一个
        Query query=Query.query(Criteria.where("toUserId").is(uid))
                .with(Sort.by(Sort.Order.desc("score")));
        return mongoTemplate.find(query,RecommendUser.class);
    }

    //通过佳人的id查询缘分值
    @Override
    public RecommendUser findByuId(Long id,Long uid) {
        Query query=Query.query(Criteria.where("userId").is(id).and("toUserId").is(uid));
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    //查看佳人信息   限制在十条数据
    @Override
    public List<RecommendUser> findAll(Long uid ,Integer count) {
      //1排除掉  在user-like数据中存储过的数据
        //1.1 查询排除掉的用户数据的id  调用 likeApi
        Query query=Query.query(Criteria.where("userId").is(uid));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId",Long.class);
        //1.2 查询所有的推荐 排除likeUserIds

        TypedAggregation<RecommendUser> typedAggregation=TypedAggregation.newAggregation(RecommendUser.class,
                Aggregation.match(Criteria.where("userId").is(uid).and("toUserId").nin(likeUserIds)),
                Aggregation.sample(count));

        AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(typedAggregation, RecommendUser.class);
        return aggregate.getMappedResults();

    }


}
